//
//  DCEmojiBoardView.m
//  xmppTest
//
//  Created by striby on 16/1/4.
//  Copyright © 2016年 com.dc. All rights reserved.
//

#import "DCEmojiBoardView.h"
@interface DCEmojiBoardView ( )
{
    NSMutableArray * emojis;
}
@end

@implementation DCEmojiBoardView

+(DCEmojiBoardView *)defaultEmojiBoardInView:(UIView *)superview
{
    static DCEmojiBoardView * emojiView =nil;
    
    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        emojiView = [[self alloc]init];
        [emojiView initBaseUIInSuperView:superview];
    });
    
    [emojiView.emojiBoardScrollView setContentOffset:CGPointMake(0, 0)];
    emojiView.pageControl.currentPage=0;
    
    
    [emojiView setFrame:CGRectMake(0, superview.bounds.size.height, emojiView.bounds.size.width, emojiView.bounds.size.height)];
    
    return emojiView;
}

-(void)initBaseUIInSuperView:(UIView*)superView
{
    [self setFrame:CGRectMake(0, superView.bounds.size.height, DCDeviceWidth, emojiBoardHeight)];
    
    
    
    _emojiBoardScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, DCDeviceWidth, emojiBoardHeight-selectionAndSenderHeight)];
    _emojiBoardScrollView.backgroundColor = [UIColor whiteColor];
    _emojiBoardScrollView.delegate=self;
    _emojiBoardScrollView.showsHorizontalScrollIndicator=NO;
    _emojiBoardScrollView.bounces=NO;
    [self addSubview:_emojiBoardScrollView];
    
    
    _emojiSelectionView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, emojiBoardHeight-selectionAndSenderHeight, DCDeviceWidth-2*selectionAndSenderHeight, selectionAndSenderHeight)];
    _emojiSelectionView.delegate=self;
    _emojiSelectionView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    
    [self addSubview:_emojiSelectionView];
    
    _senderBtn = [[UIButton alloc]initWithFrame:CGRectMake(DCDeviceWidth-2*selectionAndSenderHeight, emojiBoardHeight-selectionAndSenderHeight, 2*selectionAndSenderHeight, selectionAndSenderHeight)];
    
    [_senderBtn setBackgroundColor:[UIColor colorWithRed:45/256.0 green:160/256.0 blue:254/256.0 alpha:1.0]];
    
    [_senderBtn setTitle:@"发送" forState:UIControlStateNormal];
    
    _senderBtn.tag = SEND_TAG;
    [_senderBtn addTarget:self action:@selector(emojiBtnEvents:) forControlEvents:UIControlEventTouchUpInside];
    
    [_senderBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    
    [self addSubview:_senderBtn];
    
    NSString * plistPath = [[NSBundle mainBundle] pathForResource:@"Emoji" ofType:@"plist" ];
    
    
    emojis = [[NSMutableArray alloc]initWithContentsOfFile:plistPath];
    
    
    int emojiCountInLine = DCDeviceWidth/emojiHeight;
    
    int currentPage = 0;
    
    int currentLine = 0;
    
    int deleteBtnCount = 0;
    
    for (int i=0; i<emojis.count; i++) {
        
        UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(((i+deleteBtnCount)%emojiCountInLine)*emojiHeight+(currentPage*DCDeviceWidth), currentLine*emojiHeight, emojiHeight, emojiHeight)];
        
        [btn setTitle:emojis[i] forState:UIControlStateNormal];
        
        btn.titleLabel.font = [UIFont systemFontOfSize:emojiFontSize];
        
        
        btn.tag = EMOJI_TAG;
        
        [btn addTarget:self action:@selector(emojiBtnEvents:) forControlEvents:UIControlEventTouchUpInside];
        
        [_emojiBoardScrollView addSubview:btn];
        
        
        
        
        
        if ((i+deleteBtnCount)%emojiCountInLine==emojiCountInLine-1) {
            currentLine++;
        }
        
        
        /**
         *  删除按钮
         */
        if (((i+deleteBtnCount)%emojiCountInLine==emojiCountInLine-2&&currentLine==2)||i==emojis.count-1) {
          
            
            UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(((i+deleteBtnCount)%emojiCountInLine+1)*emojiHeight+(currentPage*DCDeviceWidth), currentLine*emojiHeight, emojiHeight, emojiHeight)];
            
            [btn setImage:[UIImage imageNamed:@"emoji_btn_delete"] forState:UIControlStateNormal];
            
            btn.tag = DELETE_TAG;
            
            [btn addTarget:self action:@selector(emojiBtnEvents:) forControlEvents:UIControlEventTouchUpInside];
            
            
            [_emojiBoardScrollView addSubview:btn];
            
            if (emojis.count-1!=i) {
                deleteBtnCount++;
                currentLine=0;
                currentPage++;
            }
            
        }
    
       
    }
    
    
    
    
    [_emojiBoardScrollView setContentSize:CGSizeMake((currentPage+1)*DCDeviceWidth, _emojiBoardScrollView.bounds.size.height)];
    _emojiBoardScrollView.pagingEnabled=YES;
    
    
    _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 3*emojiHeight, DCDeviceWidth, emojiBoardHeight-selectionAndSenderHeight-3*emojiHeight)];
    _pageControl.numberOfPages=currentPage+1;
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor darkGrayColor];
    [self addSubview:_pageControl];
 
    
    UIImageView * line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, .5)];
    [line setImage:[UIImage imageNamed:@"case_cell_Line"]];
    [self addSubview:line];
}

-(void)emojiBtnEvents:(UIButton*)sender
{
    if(self.delegate)
    {
        if ([self.delegate respondsToSelector:@selector(emojiItemPressed:)]) {
            [self.delegate emojiItemPressed:sender];
        }
    }
}

#pragma mark - scrollview delegate
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView==_emojiBoardScrollView) {
        
        int pageIndex = scrollView.contentOffset.x/DCDeviceWidth;
        
        _pageControl.currentPage = pageIndex;
        
    }
}

#pragma mark 判断是否有emoji 

-(void)showEmojiBoardWithDuration:(float)duration isUsingAnination:(BOOL)useAnimation animations:(void (^ __nullable)(void))animations completion:(void (^ __nullable)(BOOL finished))completion;
{
    if (useAnimation) {
        [UIView animateWithDuration:duration animations:^{
            [self setFrame:CGRectMake(0, self.superview.bounds.size.height-emojiBoardHeight, self.bounds.size.width, self.bounds.size.height)];
            if (animations) {
                animations();
            }
        }completion:^(BOOL finished) {
            if (completion) {
                completion(finished);
            }
        }];

    }
   else
   {
       [self setFrame:CGRectMake(0, self.superview.bounds.size.height-emojiBoardHeight, self.bounds.size.width, self.bounds.size.height)];
       if (animations) {
           animations();
       }
       if (completion) {
           completion(YES);
       }
   }
}

-(void)hideEmojiBoardWithDuration:(float)duration isUsingAnination:(BOOL)useAnimation animations:(void (^ __nullable)(void))animations completion:(void (^ __nullable)(BOOL finished))completion;
{
    
    if (useAnimation) {
        [UIView animateWithDuration:duration animations:^{
            [self setFrame:CGRectMake(0, self.superview.bounds.size.height, self.bounds.size.width, self.bounds.size.height)];
            
            if (animations) {
                animations();
            }
        }completion:^(BOOL finished) {
            if (completion) {
                completion(finished);
            }
        }];

    }
    else
    {
        [self setFrame:CGRectMake(0, self.superview.bounds.size.height, self.bounds.size.width, self.bounds.size.height)];
        
        if (animations) {
            animations();
        }
        if (completion) {
            completion(YES);
        }
    }
}


//判断是否是 emoji表情
+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         
         const unichar hs = [substring characterAtIndex:0];
         // surrogate pair
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     returnValue = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 returnValue = YES;
             }
             
         } else {
             // non surrogate
             if (0x2100 <= hs && hs <= 0x27ff) {
                 returnValue = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 returnValue = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 returnValue = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 returnValue = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                 returnValue = YES;
             }
         }
     }];
    
    return returnValue;
}


@end
